package com.cht.commonUtil.deployment;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.as.cli.CommandContext;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;

import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;

public class ReloadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/text");
		String serverGroupId = request.getParameter("serverGroupId");
		String reloadFn = request.getParameter("reloadFn");
		String envId = request.getParameter("envId");
		//取得部署記錄的ID
		int depmainSN = Integer.parseInt( request.getParameter("depmainSN") );
		String sql = "SELECT cip,cport,cid,cpwd FROM mpsquadenv WHERE subsysId=? AND envId=? AND squadId=?";
		String subsysId = "fOrder";
        
        
        Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
        String res = "";
        
		CommandContext cmdCtx = null;
		ModelControllerClient client = null;
		ModelNode requestNode = null;
		ModelNode result = null;
		
		try {
			conn= Widgets.getConn();
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			ps.setString(2, envId);
			ps.setString(3, serverGroupId);
			rs = ps.executeQuery();
			rs.next();
			
			String cip = rs.getString("cip");
			int cport = rs.getInt("cport");
			String cid = rs.getString("cid");
			char[] cpwd = rs.getString("cpwd").toCharArray();
			
			cmdCtx = Widgets.initCommandContext(cip,cport,cid,cpwd);
			client = cmdCtx.getModelControllerClient();
			if (cmdCtx.getExitCode() == 0 && !cmdCtx.isTerminated()) {
				int fDepdetailid = Widgets.getfDepdetailid(depmainSN);
				//8	重新上下(下)
				keelog(conn,ps,8,depmainSN,fDepdetailid,cip,serverGroupId,Widgets.cDT(),reloadFn, envId);
				requestNode = cmdCtx.buildRequest( "undeploy " + reloadFn + " --server-groups="+serverGroupId+" --keep-content" );
				result = client.execute(requestNode);
				updateStatus(conn, ps, Widgets.cDT(), result.toString(),depmainSN, fDepdetailid);
				//9	重新上下(上)
				fDepdetailid = Widgets.getfDepdetailid(depmainSN);
				keelog(conn,ps,9,depmainSN,fDepdetailid,cip,serverGroupId,Widgets.cDT(),reloadFn, envId);
				requestNode = cmdCtx.buildRequest( "deploy --name=" + reloadFn + " --server-groups="+ serverGroupId );
				result = client.execute(requestNode);
				updateStatus(conn, ps, Widgets.cDT(), result.toString(),depmainSN, fDepdetailid);
				res = result.get("outcome").toString().substring(1, result.get("outcome").toString().length()-1);
			}
		} catch (Exception e) {
			res = Widgets.errLog(e);
			sql = "UPDATE fdepdetail SET eDT=?,depResult=? WHERE depmainSN=? AND fdepdetailid=?";
			int fDepdetailid = Widgets.getfDepdetailid(depmainSN)-1;
			System.out.println("部署失敗了，問題是因為："+e.toString() );
			try {
				ps = conn.prepareStatement(sql);
				ps.setTimestamp(1, Widgets.cDT() );
				ps.setString(2, res );
				ps.setInt(3, depmainSN);
				ps.setInt(4, fDepdetailid);
				ps.execute();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}
			} catch (SQLException e) {e.printStackTrace();}
			if ( client != null) {client.close();}
			if ( cmdCtx != null) {cmdCtx.disconnectController();}
		}
		
        response.getWriter().write(res);
	}

	private void keelog(Connection conn,PreparedStatement ps,int status,int depmainSN,int fdepdetailid,String cip,String squadId,Timestamp cDT,String fileName,String envId) throws SQLException {
		String sql = "INSERT INTO fdepdetail (depmainSN,fdepdetailid,fDepActTypeId,hostIP,squadId,bDT,depFN,envId) VALUES(?,?,?,?,?,?,?,?)";
		ps = conn.prepareStatement(sql);
		ps.setInt(1, depmainSN);
		ps.setInt(2, fdepdetailid);
		ps.setInt(3, status);		
		ps.setString(4, cip);
		ps.setString(5, squadId);
		ps.setTimestamp(6, cDT );
		ps.setString(7, fileName);
		ps.setString(8, envId);
		ps.execute();
	}
	
	private void updateStatus(Connection conn,PreparedStatement ps,Timestamp cDT,String depResult,int depmainSN,int fdepdetailid) throws SQLException {
		String sql = "UPDATE fdepdetail SET eDT=?,depResult=? WHERE depmainSN=? AND fdepdetailid=?";
		ps = conn.prepareStatement(sql);
		ps.setTimestamp(1, cDT );
		ps.setString(2, depResult );
		ps.setInt(3, depmainSN);
		ps.setInt(4, fdepdetailid);
		ps.execute();
	}
}
